
#include "http.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>

#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>

static int http_post_response(pST_HTTP http, unsigned char *data, int data_len, void *arg)
{
	int len = 0;
	unsigned char buffer[1024] = {0};

	snprintf((char *)buffer, sizeof(buffer), "POST %s HTTP/1.1\r\n" \
									"Host: %s\r\n" \
									"Content-type: application/json\r\n" \
									"Content-length: %d\r\n" \
									"Connection: close\r\n\r\n", http->filename, http->domain, data_len);

	len = strlen((char *)buffer);
	memcpy(&buffer[len], data, data_len);
	len += data_len;

	printf("%s\n", buffer);
	write(http->fd, buffer, len);

	//if(NULL != arg)
	//{
		memset(buffer, 0, sizeof(buffer));
		read(http->fd, buffer, sizeof(buffer));
		
		printf("%s\n", buffer);
	//}
	return 0;
}

static void http_post_no_response(pST_HTTP http, unsigned char *data, int data_len)
{
	http_post_response(http, data, data_len, NULL);
}

static void http_close(pST_HTTP http)
{
	if(0 < http->fd)
	{
		close(http->fd);
		http->fd = -1;
	}
}

static int http_connect(pST_HTTP http)
{
	struct sockaddr_in remote_addr;

	struct hostent hostinfo, *phost = NULL;
	char dns_buff[8192] = {0};
	int rc = 0;

	if(0 == gethostbyname_r((char *)http->domain, &hostinfo, dns_buff, sizeof(dns_buff), &phost, &rc))
	{
		http->fd = socket(AF_INET, SOCK_STREAM, 0);
		
		if(0 < http->fd)
		{
			memset(&remote_addr, 0, sizeof(remote_addr));

			remote_addr.sin_family = AF_INET;
			remote_addr.sin_port = htons(http->port);
			remote_addr.sin_addr.s_addr = *(in_addr_t*)phost->h_addr_list[0];
			
			if(0 == connect(http->fd, (struct sockaddr *)&remote_addr, sizeof(struct sockaddr)))
			{
				return 0;
			}
		}
		http->close(http);
	}

	return -1;
}

static void http_release(pST_HTTP *http)
{
	if(NULL != http && NULL != *http)
	{
		(*http)->close(*http);
		free(*http);
		*http = NULL;
	}
}

pST_HTTP http_init(unsigned char *domain, int port, unsigned char *filename)
{
	pST_HTTP http = (pST_HTTP)calloc(1, sizeof(*http));

	if(NULL != http)
	{
		strncpy((char *)http->domain, (const char *)domain, sizeof(http->domain));
		http->port = port;
		strncpy((char *)http->filename, (const char *)filename, sizeof(http->filename));

		http->fd = -1;

		http->release = http_release;
		http->connect = http_connect;
		http->close = http_close;
		http->post_n = http_post_no_response;
		http->post = http_post_response;
	}

	return http;
}